<template>
  <div class="backtest-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>策略回测</span>
        </div>
      </template>
      <el-form ref="backtestForm" :model="backtestConfig" label-width="120px">
        <el-form-item label="选择策略" prop="strategyId" :rules="[{ required: true, message: '请选择策略', trigger: 'change' }]">
          <el-select v-model="backtestConfig.strategyId" placeholder="请选择策略">
            <el-option v-for="strategy in strategies" :key="strategy.id" :label="strategy.name" :value="strategy.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate" :rules="[{ required: true, message: '请选择开始日期', trigger: 'change' }]">
          <el-date-picker v-model="backtestConfig.startDate" type="date" placeholder="请选择开始日期" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate" :rules="[{ required: true, message: '请选择结束日期', trigger: 'change' }]">
          <el-date-picker v-model="backtestConfig.endDate" type="date" placeholder="请选择结束日期" />
        </el-form-item>
        <el-form-item label="初始资金" prop="initialCapital" :rules="[{ required: true, message: '请输入初始资金', trigger: 'blur' }, { type: 'number', min: 1, message: '初始资金必须大于0', trigger: 'blur' }]">
          <el-input v-model.number="backtestConfig.initialCapital" placeholder="请输入初始资金" />
        </el-form-item>
        <el-form-item label="手续费率(%)" prop="feeRate" :rules="[{ required: true, message: '请输入手续费率', trigger: 'blur' }, { type: 'number', min: 0, max: 100, message: '手续费率必须在0-100之间', trigger: 'blur' }]">
          <el-input v-model.number="backtestConfig.feeRate" placeholder="请输入手续费率" />
        </el-form-item>
        <el-form-item label="策略参数" v-if="selectedStrategy">
          <div v-for="(param, index) in selectedStrategy.params" :key="index" class="param-item">
            <el-input :value="param.name" disabled style="width: 150px; margin-right: 10px;" />
            <el-input v-model.number="param.value" placeholder="参数值" style="width: 150px;" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="runBacktest">运行回测</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card v-if="backtestResult" class="result-card">
      <template #header>
        <div class="card-header">
          <span>回测结果</span>
          <el-button type="primary" size="small" @click="exportReport">导出报告</el-button>
        </div>
      </template>
      <div class="result-stats">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">总收益</div>
            <div class="stat-value">{{ backtestResult.profit }}</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">最大回撤</div>
            <div class="stat-value">{{ backtestResult.maxDrawdown }}%</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">胜率</div>
            <div class="stat-value">{{ backtestResult.winRate }}%</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">年化收益率</div>
            <div class="stat-value">{{ backtestResult.annualReturn }}%</div>
          </div>
        </el-card>
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">交易次数</div>
            <div class="stat-value">{{ backtestResult.trades }}</div>
          </div>
        </el-card>
      </div>
      <div class="result-chart">
        <div ref="equityChart" class="chart-container"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';

const route = useRoute();
const backtestForm = ref(null);
const strategies = ref([]);
const selectedStrategy = ref(null);
const backtestResult = ref(null);
const equityChart = ref(null);
const backtestConfig = reactive({
  strategyId: route.query.strategyId || '',
  startDate: '',
  endDate: '',
  initialCapital: 10000,
  feeRate: 0.1
});

// 模拟数据
const mockStrategies = [
  { id: 1, name: 'MACD交叉策略', params: [{ name: 'fastPeriod', value: 12 }, { name: 'slowPeriod', value: 26 }, { name: 'signalPeriod', value: 9 }] },
  { id: 2, name: 'RSI超买超卖策略', params: [{ name: 'rsiPeriod', value: 14 }, { name: 'overbought', value: 70 }, { name: 'oversold', value: 30 }] },
  { id: 3, name: '布林带策略', params: [{ name: 'period', value: 20 }, { name: 'stdDev', value: 2 }] }
];

onMounted(() => {
  fetchStrategies();
  // 如果路由中有strategyId，自动选择该策略
  if (backtestConfig.strategyId) {
    setTimeout(() => {
      selectStrategy(backtestConfig.strategyId);
    }, 500);
  }
  // 设置默认日期为最近30天
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - 30);
  backtestConfig.startDate = startDate;
  backtestConfig.endDate = endDate;
});

watch(() => backtestConfig.strategyId, (newVal) => {
  if (newVal) {
    selectStrategy(newVal);
  } else {
    selectedStrategy.value = null;
  }
});

function fetchStrategies() {
  // 模拟API请求
  setTimeout(() => {
    strategies.value = mockStrategies;
  }, 500);
}

function selectStrategy(id) {
  const strategy = strategies.value.find(item => item.id === parseInt(id));
  if (strategy) {
    selectedStrategy.value = { ...strategy };
  }
}

function runBacktest() {
  backtestForm.value.validate((valid) => {
    if (valid) {
      // 模拟回测请求
      ElMessage({
        type: 'info',
        message: '回测开始运行，请稍候...'
      });
      setTimeout(() => {
        // 模拟回测结果
        backtestResult.value = {
          profit: '¥2,345.67',
          maxDrawdown: 8.2,
          winRate: 58.3,
          annualReturn: 35.7,
          trades: 24
        };
        // 初始化净值曲线
        initEquityChart();
        ElMessage({
          type: 'success',
          message: '回测完成'
        });
      }, 2000);
    } else {
      return false;
    }
  });
}

function initEquityChart() {
  // 模拟净值数据
  const dates = [];
  const equity = [];
  const startDate = new Date(backtestConfig.startDate);
  const endDate = new Date(backtestConfig.endDate);
  let currentDate = new Date(startDate);
  let currentEquity = backtestConfig.initialCapital;
  equity.push(currentEquity);
  dates.push(formatDate(currentDate));
  
  while (currentDate < endDate) {
    currentDate.setDate(currentDate.getDate() + 1);
    // 模拟净值波动
    const change = currentEquity * (Math.random() - 0.48) * 0.02;
    currentEquity += change;
    equity.push(currentEquity);
    dates.push(formatDate(currentDate));
  }
  
  const chart = echarts.init(equityChart.value);
  const option = {
    title: {
      text: '净值曲线',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        interval: Math.floor(dates.length / 10) // 只显示10个标签
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: equity,
      type: 'line',
      smooth: true
    }]
  };
  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

function formatDate(date) {
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
}

function resetForm() {
  backtestForm.value.resetFields();
  backtestResult.value = null;
}

function exportReport() {
  // 模拟导出报告
  ElMessage({
    type: 'success',
    message: '报告导出成功'
  });
}
</script>

<style scoped>
.backtest-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-card {
  margin-top: 20px;
}

.result-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1 1 150px;
  min-width: 150px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #1f2329;
}

.result-chart {
  width: 100%;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.param-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>